package net.sk.china.city.talk.utils;

import cn.hutool.core.collection.CollUtil;
import net.sk.china.city.talk.utils.MenusResponse;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 菜单树
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 聊来 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2024/6/2 14:48
 * +----------------------------------------------------------------------
 */
public class MenuTreeUtil {

    private List<MenusResponse> menuList;

    public MenuTreeUtil(List<MenusResponse> menuList) {
        this.menuList = menuList;
    }

    /**
     * 建立树形结构
     * @return List<MenusResponse>
     */
    public List<MenusResponse> buildTree(){
        List<MenusResponse> treeMenus = new ArrayList<>();
        for(MenusResponse menuNode : getRootNode()) {
            menuNode = buildChildTree(menuNode);
            treeMenus.add(menuNode);
        }
        return sortList(treeMenus);
    }


    /**
     * 排序
     * @param treeMenus 菜单
     * @return List<MenusResponse>
     */
    private List<MenusResponse> sortList(List<MenusResponse> treeMenus) {
        treeMenus = treeMenus.stream().sorted(Comparator.comparing(MenusResponse::getSort).reversed()).collect(Collectors.toList());
        treeMenus.forEach(e -> {
            if (CollUtil.isNotEmpty(e.getChildList())) {
                e.setChildList(sortList(e.getChildList()));
            }
        });
        return treeMenus;
    }

    /**
     * 递归，建立子树形结构
     * @param pNode 菜单
     * @return MenusResponse
     */
    private MenusResponse buildChildTree(MenusResponse pNode){
        List<MenusResponse> childMenus = new ArrayList<>();
        for(MenusResponse menuNode : menuList) {
            if(menuNode.getPid().equals(pNode.getId())) {
                childMenus.add(buildChildTree(menuNode));
            }
        }
        pNode.setChildList(childMenus);
        return pNode;
    }

    /**
     * 获取根节点
     * @return List<MenusResponse>
     */
    private List<MenusResponse> getRootNode() {
        List<MenusResponse> rootMenuLists = new  ArrayList<>();
        for(MenusResponse menuNode : menuList) {
            if(menuNode.getPid().equals(0)) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}
